package com.earl.eatbao.web;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.earl.eatbao.commons.vo.ResultMessage;
import com.earl.eatbao.domain.eatbao.UserInfo;
import com.earl.eatbao.domain.sercurity.User;
import com.earl.eatbao.security.shiro.ShiroPrincipal;
import com.earl.eatbao.service.UserService;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping(value = "/users")
//@Api(value="Person Rest Service") //修改生成的son路径
public class UserController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 用户账号服务
     */
    @Autowired
    private UserService userService;
    
    /**
     * GET /users -> get all the users
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "得到所有用户信息", notes = "find All User", httpMethod = "GET", response = User.class, responseContainer = "List")
    public ResponseEntity<ResultMessage> getAll() {
        logger.info("<====== 进入getAll:方法,{[] : } ====");

       // desc: 封装操作结果
       ResultMessage result = new ResultMessage();
       result.getResultParm().put("userList",userService.findAll());
       result.setMessageCode(200l);
       result.setResultInfo("请求操作成功");

       logger.info("==== 退出getAll方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
       return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
    }

    /**
     * GET /users/:id -> get the "id" user
     */
    @Valid
    @ApiOperation(value = "得到id指定用户", notes = "GET POINT USER", httpMethod = "GET", response = String.class)
    @RequestMapping(value = "/id={id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResultMessage> getUser(
            @ApiParam(required = true, name = "id", value = "用户id")
            @NotNull(message = "用户id不能为空") 
            @PathVariable
            Long id) {
        logger.info("<====== 进入getUser:方法,{[id] :" + id + " } ====");
        ResultMessage result = new ResultMessage();
        User user = userService.findOne(id);
        if (user != null) {
            result.setServiceResult(true);
            result.getResultParm().put("user", user);
        } else {
            result.setServiceResult(false);
            result.setResultInfo("获取用户失败");
        }

        logger.info("==== 退出getUser方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
        return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
    }

    /**
     * 更新指定用户.
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "更新指定用户", notes = "UPDATE ONE USER", httpMethod = "POST", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "User's name", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "realName", value = "User's email", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "User ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "loginid", value = "User ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "userImg", value = "User ID", required = false, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "safePassword", value = "User ID", required = false, dataType = "long", paramType = "query")
    })
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> update(
            @ApiParam(required = false, name = "user", value = "这个字段不要理！！！！")
            User user) {
        ResultMessage result = new ResultMessage();
        if (userService.save(user) != null) {
            result.setServiceResult(true);
            result.setResultInfo("更新成功");
        } else {
            result.setServiceResult(false);
            result.setResultInfo("更新失败");
        }

        logger.info("==== 退出update方法 返回值类型:{ ResponseEntity<?>: } =======>");
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @Valid
    @ApiOperation(value = "删除一个用户", notes = "DELETE ONE USER", httpMethod = "DELETE", response = String.class)
    @RequestMapping(value = "/deleteById", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> deleteById(
            @ApiParam(required = true, name = "id", value = "用户id")
            @NotNull(message = "用户id不能为空")
            @RequestParam(name = "id", required = true)
            Long id) {

        logger.info("<====== 进入deleteById:方法,{[id] : " + id + " } ====");
        userService.delete(id);
        // desc: 封装操作结果
        ResultMessage result = new ResultMessage();
        result.setServiceResult(true);
        result.setMessageCode(200l);
        result.setResultInfo("请求操作成功");

        logger.info("==== 退出deleteById方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
        return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
    }

    /**
     * POST /change -> changes the current user's password
     */
    @Valid
    @ApiOperation(value = "更改用户密码", notes = "CHANGE USER PASSWORD", httpMethod = "POST", response = String.class)
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResultMessage> changePassword(
            @ApiParam(required = true, name = "oldPassword", value = "旧密码")
            @RequestParam(name = "oldPassword", required = true)
            String oldPassword,
            @ApiParam(required = true, name = "id", value = "用户id")
            @NotNull(message = "用户id不能为空")
            @RequestParam(name = "id", required = true)
            Long id,
            @ApiParam(required = true, name = "newPassword", value = "新密码")
            @RequestParam(name = "newPassword", required = true)
            @Length(min = 5, max = 32)
            String newPassword) {

        logger.info("<====== 进入changePassword:方法,{[oldPassword, id, newPassword] : } ====");
        // desc: 封装操作结果
        ResultMessage result = new ResultMessage();
        result.setServiceResult(userService.changePassword(id, oldPassword, newPassword));
        result.setMessageCode(200l);
        result.setResultInfo("请求操作成功");

        logger.info("==== 退出changePassword方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
        return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
    }

    /**
     * 用户登录
     *
     * @param account
     * @param password
     * @return
     */
    @Valid
    @RequestMapping(value = "/doLogin", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    @ApiOperation(value = "登录系统", notes = "loginSystem", httpMethod = "POST", response = String.class)
    public ResponseEntity<ResultMessage> doLogin(
            @ApiParam(required = true, name = "account", value = "用户账号")
            @NotEmpty(message = "登录账号不能为空")
            @RequestParam(name = "account", required = true)
            String account,
            @ApiParam(required = true, value = "用户登录密码")
            @RequestParam(name = "password", required = true) String password) {
        logger.info("<====== 进入doLogin:方法,{[account, password] :" + account + ":" + password + " } ====");

        userService.doLogin(account, password);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setResultInfo("登录成功");
        ShiroPrincipal principal = (ShiroPrincipal) SecurityUtils.getSubject().getPrincipal();
        User user = principal.getUser();

        resultMessage.getResultParm().put("user", user);
        logger.info("==== 退出doLogin方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
        return new ResponseEntity<ResultMessage>(resultMessage, HttpStatus.OK);
    }

    /**
     * 上传图片
     */
//    @Valid
//    @ApiOperation(value = "更新用户头像", notes = "loginSystem", httpMethod = "POST", response = String.class)
//    @RequestMapping(value = "/updateImg", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
//    public ResultMessage updateImg(
//            MultipartFile userfile,
//            @NotNull(message = "用户id不能为空")
//            @ApiParam(required = true, name = "id", value = "用户id")
//            Long id) {
//        ResultMessage result = new ResultMessage();
//        if (userService.updateImg(userfile, id)) {
//            User user = userService.findOne(id);
//            result.setResultInfo("更新用户头像成功");
//            result.setServiceResult(true);
//            result.getResultParm().put("user",user);
//        } else {
//            result.setResultInfo("更新用户头像失败");
//            result.setServiceResult(false);
//        }
//        return result;
//    }

    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation(value = "得到用户信息", notes = "user info", httpMethod = "GET", response = String.class)
    @RequestMapping(value = "/info", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ShiroPrincipal> loginInfo2() {
        Subject subject = SecurityUtils.getSubject();
        //TODO  这里你要弄什么？
        //可以通过下面这个对象，动态修改用户权限信息
        ShiroPrincipal principal = (ShiroPrincipal) subject.getPrincipal();
        System.out.println(principal.toString());
        return new ResponseEntity<ShiroPrincipal>(principal, HttpStatus.OK);
    }

    /**
     * 用户注册
     * @param account
     * @param password
     * @param verifycode
     * @return
     */
    @Valid
    @ApiOperation(value = "用户注册", notes = "user register system account ", httpMethod = "POST", response = String.class)
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ResultMessage> regitsterAccount(
            @ApiParam(required = true, name = "account", value = "用户登录账号")
            @NotEmpty(message = "注册账号不能为空")
            @RequestParam(name = "account", required = true)
            String account,
            @ApiParam(required = true, name = "password", value = "用户登录密码")
            @NotEmpty(message = "登录密码不能为空")
            @RequestParam(name = "password", required = true)
            String password,
            @ApiParam(required = true, name = "verifycode", value = "用户登录密码")
            @NotEmpty(message = "输入验证码不能为空")
            @RequestParam(name = "verifycode", required = true)
            String verifycode) {

        logger.info("<====== 进入regitsterAccount:方法,{[account, password, verifycode] : } ====");
        // desc: 封装操作结果
        ResultMessage result = new ResultMessage();
        result.setServiceResult(userService.registerAccount(account, password,verifycode));
        result.setMessageCode(200l);
        if (result.getServiceResult()) {
            result.setResultInfo("注册成功");
        } else {
            result.setResultInfo("注册失败");
        }

        logger.info("==== 退出regitsterAccount方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
        return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
    }

    /**
     * 查看用户的普通角色信息
     * @param userId 系统用户id
     * @return
     */
    @ApiOperation(value = "查找指点用户信息", notes = "查找指点用户信息", httpMethod = "POST", response = String.class)
    @RequestMapping(value="/findUserInfo",  method = RequestMethod.POST)
    public ResponseEntity<ResultMessage> findUserInfo(
            @ApiParam(name = "userId", required = true, value = "用户ID")
            @RequestParam(name = "userId", required = true) Long userId) {
        logger.info("<====== 进入findUserInfo:方法,{[userId] :" + userId + " } ====");

    	UserInfo userInfo = userService.findUserInfo(userId);
    	// desc: 封装操作结果
    	ResultMessage result = new ResultMessage();
    	result.getResultParm().put("userInfo",userInfo);
    	result.setMessageCode(200l);
    	result.setResultInfo("请求操作成功");

    	logger.info("==== 退出findUserInfo方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
    	return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
    }

    /**
     * 忘记密码
     * @param account 用户登录账号
     * @return
     */
    @ApiOperation(value = "重置密码", notes = "重置密码", httpMethod = "POST", response = String.class)
    @RequestMapping(value="/resetPassword",  method = RequestMethod.POST)
    public ResponseEntity<ResultMessage> resetPassword(
            @ApiParam(name = "account", required = true, value = "账号")
            @RequestParam(name = "account", required = true)
            String account,
            @ApiParam(name = "password", required = true, value = "密码")
            @RequestParam(name = "password", required = true)
                    String password,
            @ApiParam(name = "verifyCode", required = true, value = "验证码")
            @RequestParam(name = "verifyCode", required = true)String verifyCode) {

        logger.info("<====== 进入resetPassword:方法,{[account, password, verifyCode] : } ====");
        // desc: 封装操作结果
        ResultMessage result = new ResultMessage();
        result.setServiceResult(userService.resetPassword(account,password,verifyCode));
        result.setMessageCode(200l);
        result.setResultInfo("请求操作成功");

        logger.info("==== 退出resetPassword方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
        return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
    }

    /**
     * 上传用户头像
     * @return
     */
    @ApiOperation(value = "用户头像上传", notes = "用户头像上传", httpMethod = "POST", response = String.class)
    @RequestMapping(value="/upLoadImage",  method = RequestMethod.POST)
    public ResponseEntity<ResultMessage> uploadUserImage(
            @ApiParam(name = "file", value = "上传文件")
            @RequestParam("file")
                    MultipartFile file,
            @ApiParam(name = "userId", required = true, value = "用户ID")
            @RequestParam(name = "userId", required = true)
                    Long userId) {

        logger.info("<====== 进入uploadUserImage:方法,{[UserId] :" + userId + " } ====");
        // desc: 封装操作结果
        ResultMessage result = new ResultMessage();

        result.setServiceResult(userService.upLoadUserImage(file, userId));
        result.setMessageCode(200l);
        if (result.getServiceResult()) {
            result.setResultInfo("请求操作成功");
        } else {
            result.setResultInfo("请求操作失败");
        }

        logger.info("==== 退出uploadUserImage方法 返回值类型:{ ResponseEntity<ResultMessage>: } =======>");
        return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
    }



}
